import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // 请求超时设置
})

// 请求拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 在请求之前处理事件
    const cookieToken = getToken()
    // 添加请求header
    cookieToken && Object.assign(config.headers, { Authorization: `Bearer ${cookieToken}` })
    // 过滤不需要token的接口
    if (config.data && config.data.deleteToken) {
      delete config.headers.common.Authorization
      delete config.data.deleteToken
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 请求结果拦截器 response interceptor
service.interceptors.response.use(
  response => {
    // 异常处理
    const res = response.data
    if (res.code !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
